package com.wa.page;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.wa.bean.MessageTemplate;
import com.wa.constants.LogCommonConstants;
import com.wa.pojo.BaseEntity;
import com.wa.pojo.EmailLogPojo;
import lombok.Getter;
import lombok.Setter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通知日志基础类
 *
 * @author Homan
 */
@Getter
@Setter
public class BaseNoticeLogEntity extends BaseEntity {
    /**
     * 收件人
     */
    private String receiver;

    /**
     * 标题
     */
    private String title;

    /**
     * 内容
     */
    private String content;


    public BaseNoticeLogEntity() {
        super();
    }


    public BaseNoticeLogEntity(Object object) {
        super();

        if (object == null) {
            return;
        }
        if (object instanceof MessageTemplate) {
            MessageTemplate messageTemplate = MessageTemplate.class.cast(object);

            LinkedHashMap<String, Object> paramMap = messageTemplate.getParamMap();
            if (paramMap != null) {
                Object templateName = paramMap.get(LogCommonConstants.MOBILE_MESSAGE_TEMPLATE_NAME_KEY);

                this.title = String.class.cast(templateName);

                Map<String, Object> contentMap = paramMap.entrySet().stream()
                        .filter(t -> t.getKey() != null && !t.getKey().equals(LogCommonConstants.MOBILE_MESSAGE_TEMPLATE_NAME_KEY))
                        .collect(Collectors.toMap(t -> t.getKey(), t -> t.getValue(), (t1, t2) -> t1));
                this.content = JSONUtil.toJsonStr(contentMap);
            }
            this.receiver = messageTemplate.getMobile();
        } else if (object instanceof EmailLogPojo) {
            EmailLogPojo emailLogPojo = EmailLogPojo.class.cast(object);

            this.title = emailLogPojo.getTitle();
            this.content = emailLogPojo.getContent();
            if (emailLogPojo.getTo() != null && emailLogPojo.getTo().length > 0) {
                this.receiver = StrUtil.join(",", emailLogPojo.getTo());
            }
        }


    }
}
